<?

require_once("../core/lib/phpmailer/class.phpmailer.php");

class AuthController extends MainController implements ControllerInterface {

	const FB_AUTHORIZE_URL = 'https://graph.facebook.com/oauth/authorize';
	const FB_TOKEN_URL = 'https://graph.facebook.com/oauth/access_token';
	const FB_PROFILE_URL = 'https://graph.facebook.com/me';
	const FB_PROFILE_PICTURE = 'https://graph.facebook.com/me/picture';
	/**  **/
	const FB_CLIENT_ID = '203389083059565';
	const FB_CLIENT_SECRET = 'ae7036caeedf01c1d6e45e50ede830c1';
	
	/**
	 * Strona glowna
	 *
	 */
	private function ClearQuiz() {
		SessionProxy::ClearValue('registration_quiz');
	}

	private function getQuiz() {
		$remembered = Sessionproxy::GetValue('registration_quiz');
		$remembered = unserialize($remembered);
		if(!is_array($remembered))$remembered = array();

		return $remembered;
	}

	public function IndexAction($param) {
		$this->AddDescription($this->t('Registration'));
		$this->AddTitle($this->t('Registration'));
		
	}
	
	public function FbRegisterValidationAction($param, $as_action = true)
	{
		if ($as_action)
				$param['validation_data'] = array();
		$validator = new Validator($param['validation_data']);
		$validator->IsEmpty('rules2', $this->t('Accept rules'));
		$this->smarty->assign('js_values', $validator->getJsValues());
		$this->smarty->assign('id_form', Request::GetGet('id_f'));
		return $validator->getErrorList();		
	}
	
	public function RegisterValidationAction($param, $as_action = true)
	{	
		
		if ($as_action)
				$param['validation_data'] = array();	
		
		$validator = new Validator($param['validation_data']);
		$validator->IsEmpty('first_name', $this->t('Enter your name'));
		$validator->IsString('field_name', $this->t('Enter your name'));
		$validator->IsEmpty('last_name', $this->t('Enter your family name'));
		$validator->IsString('last_name', $this->t('Enter your family name'));
		$validator->IsEmailAddress('email', $this->t('Enter your email'));
		$validator->IsEmpty('email', $this->t('Enter your email'));
		$validator->IsEmpty('email2', $this->t('Reenter your email'));
		$validator->IsNotEqual('email2', 'email', $this->t('Emails aren\'t same'));
		$validator->IsShorter('password', 4, $this->t('Password should be longer than 4 characters'));
		$validator->IsEmpty('password', $this->t('Enter password'));
		$validator->IsEmpty('password2', $this->t('Reenter your password'));
		$validator->IsNotEqual('password2', 'password', $this->t('Passwords aren\'t same'));
		$validator->IsValidOnline('email', $this->t('Specified email address is already registered'), Router::GenerateUrl('ajaxCheckEmail'));
		$validator->IsEmpty('rules1', $this->t('Accept rules'));
		$this->smarty->assign('js_values', $validator->getJsValues());
		$this->smarty->assign('id_form', Request::GetGet('id_f'));
		return $validator->getErrorList();		
	}
	
	public function AjaxCheckEmailAction($param) {
		$this->setAjaxRender();
		$this->partialTemplate = 'clean.tpl';

		$email = Request::GetGet('email');

		$dalData = UserDAL::GetDalDataObj();
		
		if($this->userLoggedIn) 
		{
			// jesli user zalogowany - moze nadpisac swoj mail
			$dalData->addCondition('id', $this->user->getId() . ' AND (email = \'' . $email . '\' OR new_email = \'' . $email . '\')' , '!=');
		} else {
			$dalData->addCondition('email', '\'' . $email . '\'', '=' , 'AND');
			$dalData->addCondition('new_email', '\'' . $email . '\'', '=' , 'OR');			
		}
		
		$res = UserDAL::GetResult($dalData);
		
		header("Content-type: text/html; charset=utf-8");
		
		echo json_encode((count($res) > 0)?false:true);
		exit;
		
		if ($res)
			$this->content = 'false';
		else
			$this->content = 'true';
	}	
	
	
	public function RegisterAction($param)
	{
		$this->AddDescription($this->t('Sign in'));
		$this->AddTitle("Sign in");
		$this->AddBreadCrumb("Sign in");
		
		if($this->userLoggedIn)
		{
			return $this->AddRedirect(Router::GenerateUrl('default'), 0);
		}	
		if(Request::IsPost() && Request::GetPost('action') == 'register')
		{
			$data = Request::GetAllPost();
			$errors = array();
			if(empty($errors))
			{
				$_now = date('Y-m-d H:i:s', time());
				$user = new User();
				$user->setStatus(1);
				$user->setActive(0);
				$user->setOnline(0);
				$user->setEmail($data['email']);
				$user->setPassword(UserDAL::GeneratePassword($data['password']));
				$user->setFirstName($data['first_name']);
				$user->setLastName($data['last_name']);
				$user->setDateInsert($_now);
				$user->setdateUpdate($_now);
//				$user->setLastLogin($_now);
				$userId = UserDAL::Insert($user->GetDalDataObj());
				
				$extProfile = new UserExtendedProfile();
				$extProfile->setIdUser($userId);
				UserExtendedProfileDAL::Insert($extProfile->GetDalDataObj());
				
				SessionProxy::SetValue('_user_id_', $userId);
				SessionProxy::SetValue('_redirect_from_register_', true);
				
				return $this->AddRedirect(Router::GenerateUrl('sendConfirmationEmail'), 0);
				
			}
		} else {
			$this->addScript('jquery-validate/jquery.validate.js');
			$this->AddScript(Router::GenerateUrl('signInValidation') . '?id_f=registerForm');
			$this->AddScript(Router::GenerateUrl('fbSignInValidation') . '?id_f=fbRegisterForm');
		}
		
	}
	
	public function SendConfirmationEmailAction($param)
	{
		$this->AddDescription($this->t('Sendig confirmation email'));
		$this->AddTitle($this->t('Sendig confirmation email'));
		
		if($this->userLoggedIn)
		{
			return $this->AddRedirect(Router::GenerateUrl('default'), 0);
		}
		
		$_isFromeregister = SessionProxy::GetValue('_redirect_from_register_', False);
		$_userId = SessionProxy::GetValue('_user_id_', 0);
		if($_isFromeregister && $_userId)
		{
			// przekierowanie z rejestracji
			SessionProxy::ClearValue('_redirect_from_register_');
			
			$user = UserDAL::GetResult(
						UserDAL::GetDalDataObj(
							array(
								'condition' => array(
									'id' => array($_userId),
									'active' => array(0)
								)
							)
						)
					);
			if(count($user) != 1)
			{
				return $this->AddRedirect(Router::GenerateUrl('default'), 0);
			}
			
			$hash = UserDAL::GenerateHash();
			
			$user[0]->setHash($hash);
			UserDAL::Update($user[0]->getDalDataObj());
			
			$this->smarty->assign('hash', $hash);
			
			$this->AddBreadCrumb($this->t('sign in'), Router::GenerateUrl('signIn'));
			$this->AddBreadCrumb($this->t('sign in confirmation'));
			
			/* @todo: wysyłąnei maila */
			// wyslanei maila
			$mail = new Mailer(MAIL_PORT);
			
			$this->smarty->assign('hash', $hash);
			$mail->Body = $this->smarty->fetch('partial/Auth/email/ConfirmRegistrationHTML.tpl');
			$mail->Subject = $this->t('Please confirm your email address');
			$mail->AddAddress($user[0]->getEmail());
			$e = $mail->Send();

			$this->smarty->assign('email', $user[0]->getEmail());
			
		} else {
			return $this->AddRedirect(Router::GenerateUrl('default'), 0);
		}
		
		
	}
	
	public function ConfirmAccountAction($param)
	{
		$this->AddDescription($this->t('Confirm account'));
		$this->AddTitle("Confirm account");
		$hash = $param['hash'];
		
		$res = UserDAL::ConfirmRegistration($hash);

		if($res)
		{
//			$this->AddRedirectInfo($this->T('Your account is active'));
			
			/* logowanie usera */
			SessionProxy::SetValue('logged_user', $res);
			$res->setOnline(0);
			$res->setHash(UserDAL::GenerateHash());
			UserDAL::Update($res->getDalDataObj());			
			
			if(SessionProxy::IsSetValue('registration_quiz')) {
				$data = $this->GetQuiz();
				$this->RunModule('Quiz','SaveRegistrationQuizData', array('user' => $res->getId(), 'data' => $data));
				$this->ClearQuiz();
				if(Registry::Get('_redirect_to_premium_'))
				{
					return $this->AddRedirect(Router::GenerateUrl('buyPremium'), 0);
				} else {
					return $this->AddRedirect(Router::GenerateUrl('editProfile'), 0);
				}
			}else{
				$this->AddRedirect(Router::GenerateUrl('registrationQuizStep1'), 0);
				
			}
			
		} else {
			$this->AddRedirectInfo($this->T('An error occurred during activation'));
			$this->AddRedirect(Router::GenerateUrl('default'), 0);
		}
		
		
	}
	
	public function LoginValidationAction($param, $as_action = true)
	{
		if ($as_action)
				$param['validation_data'] = array();	
		
		$validator = new Validator($param['validation_data']);
		$validator->IsEmpty('login', $this->t('Enter your email'));
		$validator->IsEmpty('password', $this->t('Enter password'));
		$this->smarty->assign('js_values', $validator->getJsValues());
		$this->smarty->assign('id_form', Request::GetGet('id_f'));
		return $validator->getErrorList();		
	}
	
	// logowanie
	public function LoginAction($param)
	{
		$this->AddDescription($this->t('Login'));
		$this->AddTitle("Login");	
		$this->AddBreadCrumb("Login");

		
		if(Request::IsPost())
		{
			if($this->userLoggedIn)
			{
				$_urls = SessionProxy::GetValue('_user_urls_history_');

				$_i = count($_urls);

				$_lastlogin = $this->user->getLastLogin();
				$this->user->setLastLogin(date('Y-m-d H:i:s', time()));
				UserDAL::Update($this->user->getDalDataObj());
				
				if($_lastlogin == '0000-00-00 00:00:00')
				{
					return $this->AddRedirect(Router::GenerateUrl('registrationQuizStep1'), 0);
				} else {
					return $this->AddRedirect(Router::GenerateUrl('default'), 0);
				}
				

			} else {
				$this->smarty->assign('loginError', true);
			}
		
		} else {
			if($this->userLoggedIn)
			{
				return $this->AddRedirect(Router::GenerateUrl('default'), 0);
			}
			$this->smarty->assign('loginError', false);
		}
		
		$this->addScript('jquery-validate/jquery.validate.js');
		$this->AddScript(Router::GenerateUrl('logInValidation') . '?id_f=loginForm');		

	}
	
	// wylogowanie
	public function LogoutAction($param)
	{
            $this->AddDescription("");
		$this->AddTitle("");
            if($this->userLoggedIn) {
			
		
		$_user = SessionProxy::GetValue('logged_user');
		$_user->setOnline(0);
		UserDAL::Update($_user->getDalDataObj());
		
		
		SessionProxy::ClearValue('logged_user');
            }
		$this->AddRedirect(Router::GenerateUrl('default'), 0);
	}
	
	public function CheckUser($param)
	{
		
		if(!empty(Router::$curLabel))
		{
			$_urls = SessionProxy::GetValue('_user_urls_history_', array());
			$_i = count($_urls);
			// jesli nie ma przekierowania na ta sama strone
			
			
			
			if(isset($_urls[$_i - 1]))
			{
				if( $_urls[$_i - 1]['label'] != Router::$curLabel) 
				{
					if($_i > 2)
					{
						array_shift($_urls);
					}
					$_urls[] = array('label'=>Router::$curLabel, 'params' => $param);
					SessionProxy::SetValue('_user_urls_history_', $_urls);				
				}
			} else {
					$_urls[] = array('label'=>Router::$curLabel, 'params' => $param);
					SessionProxy::SetValue('_user_urls_history_', $_urls);					
			}
		}
		
		
		//czy i skąd się logujemy
		$login_action = Request::Check('login_action') ? Request::GetPost('login_action') : null;
		
		$user = null;
		$msg = null;

		switch($login_action)
		{
			case 'login':
				$login = Request::GetPost('login');
				$password = Request::GetPost('password');

				$_user = UserDAL::GetResult(
						UserDAL::GetDalDataObj(array(
							'condition' => array(
								'email' => array($login),
								'password' => array(UserDAL::GeneratePassword($password)),
								'active' => '1'
							)
						)));


				if(isset($_user[0]) && count($_user) == 1)
				{
					
					$status = 1;
					
					SessionProxy::SetValue('logged_user', $_user[0]);
					$user = $_user[0];
					$status = $user->getStatus();
					$user->setStatus(1);
					$user->setOnline(0);
					UserDAL::Update($user->getDalDataObj());
					if(Router::$curLabel != 'logIn')
					{
						if($status == 99)
						{
							$this->AddRedirect(Router::GenerateUrl('registrationQuizStep1'), 0);
						} else {
							$this->AddRedirect(Router::GenerateUrl('default'), 0);
						}						
					}
				}					
				break;

			case 'logout':

				break;

			// sprawdzamy usera
			default:
				UserDAL::ReloadUser();
				$user = SessionProxy::GetValue('logged_user');
		}

		return array($user, !is_null($user), $msg);
	}		
	



	/**
	 * Czesc wspolna wszystkich podstron
	 *
	 */
	public function PreDispatch($param) {
		$this->Run($param);
	}

	public function PostDispatch($param) {
		
		// nagłówek strony
		$this->RunShared('Header', $param);
		
		// footer
		$this->RunShared('Footer', $param);
	}
	
	public function FbRegisterAction()
	{
		try {
			$data = array(
				'client_id' => self::FB_CLIENT_ID,
				'redirect_uri' => Router::GenerateUrl('fbVerify'),
				'type' => 'web_server',
				'scope' => 'email,user_birthday'
			);

			header('Location: ' . self::FB_AUTHORIZE_URL . '?' . http_build_query($data, null, '&'));
			die();
		} catch (Exception $e)
		{
			
		}
		
	}
	
	public function FbVerifyAction()
	{
		
		
		try {
			
			$this->AddDescription($this->t("Thank you for registration"));
			$this->AddTitle($this->t("Thank you."));
			
			$this->AddBreadCrumb($this->t('sign in'), Router::GenerateUrl('signIn'));
			$this->AddBreadCrumb($this->t('sign in confirmation'));
			
			$data = array(
				'client_id' => self::FB_CLIENT_ID,
				'redirect_uri' => Router::GenerateUrl('fbVerify'),
				'client_secret' => self::FB_CLIENT_SECRET,
				'code' => $_GET['code'],
			);

//			// Get an access token
			$result = @file_get_contents(self::FB_TOKEN_URL . '?' . http_build_query($data, null, '&'));
			parse_str($result, $result_array);

			// Make sure we actually have a token
			if (empty($result_array['access_token']))
				throw new Exception('Invalid response received from Facebook. Response = "' . $result . '"');

			// Grab the user's data
			$access_token = $result_array['access_token'];
			$fbUser = json_decode(file_get_contents(self::FB_PROFILE_URL . '?access_token=' . $access_token));
			if ($fbUser == null)
				throw new Exception('Invalid user data returned from Facebook');
			
			$result = UserDAL::GetResult(
					UserDAL::GetDalDataObj(
						array(
							'condition' => array(
								'email' => $fbUser->email
							)
						)
					)
				);

			
			if(isset ($result[0]))
			{
				$this->smarty->assign('user_exists', true);
			} else {

				// obrazek
				$imgData = array(
					'type' => 'large',
					'access_token' => $access_token
				);
				
				$fbImg = new FbAvatarDownloader();
				$avatarPath = $fbImg->download(self::FB_PROFILE_PICTURE . '?' . http_build_query($imgData, null, '&'), PATH_STATIC . '/upload/user/avatar/');
				
				$_now = date('Y-m-d H:i:s', time());
				
				// generate password
				$password = substr(md5($_now), 1, 6);
				// create user
				
				// location - 
				$cityId = null;
				
				$country = null;
				$state = null;
				$city = null;
				
				if(isset($fbUser->location))
				{
					$cityId = $fbUser->location->id;
				} else if (isset($fbUser->hometown))
				{
					$cityId = $fbUser->hometown->id;
				}
				
				if($cityId)
				{
					$info = @file_get_contents('https://graph.facebook.com/' . $cityId);
					$place = json_decode($info);
					if(isset($place->location))
					{
						$placeInfo = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=' . $place->location->latitude . ',' . $place->location->longitude . '&sensor=false');
						$placeData = json_decode($placeInfo);
						foreach($placeData->results[0]->address_components as $infoData)
						{	
							if(in_array('country', $infoData->types))
							{
								$country = $infoData->long_name;
							}
							if(in_array('administrative_area_level_1', $infoData->types))
							{
								$state = $infoData->long_name;
							}
							if(in_array('administrative_area_level_3', $infoData->types))
							{
								$city = $infoData->long_name;
							}							
						}
					}
					
				}
				// end location
				
				$user = new User();
				$user->setGender(($fbUser->gender=='male'?1:2));
				
				$user->setCity($city);
				$user->setLocation($country);
				$user->setState($state);
				
				$user->setStatus(99);
				$user->setActive(1);
				$user->setOnline(0);
				$user->setEmail($fbUser->email);
				$user->setPassword(UserDAL::GeneratePassword($password));
				$user->setFirstName($fbUser->first_name);
				$user->setLastName($fbUser->last_name);
				$user->setDateInsert($_now);
				$user->setdateUpdate($_now);
				$user->setAvatar( str_replace(PATH_STATIC, '', $avatarPath) );
				$user->setBirthDate(date("Y-m-d", strtotime($fbUser->birthday)));
				
				$userId = UserDAL::Insert($user->GetDalDataObj());

				$extProfile = new UserExtendedProfile();
				$extProfile->setIdUser($userId);
				UserExtendedProfileDAL::Insert($extProfile->GetDalDataObj());

				SessionProxy::SetValue('_user_id_', $userId);
				SessionProxy::SetValue('_redirect_from_register_', true);

				
				$mail = new Mailer(MAIL_PORT);

				$this->smarty->assign('user', $user);
				$this->smarty->assign('password', $password);
				$mail->Body = $this->smarty->fetch('partial/Auth/email/FacebookValidationHTML.tpl');
				$mail->Subject = $this->t('Your password for tennizoom.com');
				$mail->AddAddress($user->getEmail());
				$mail->Send();	

				$this->smarty->assign('email', $user->getEmail());
				$this->smarty->assign('user_exists', false);
			}
			
			// send email
			
			// display OK
		}catch (Exception $e) {

		}
	} 

	public function RemindPasswordAction($param) {
		if ($this->userLoggedIn
			)$this->AddRedirect(Router::GenerateUrl('default', array()), 0);
		$this->addDescription($this->t('Password remind/reset'));
		$this->addTitle($this->t('Password remind/reset'));
		$this->addBreadCrumb($this->t('Password remind/reset'));

		$this->addScript(Router::GenerateUrl('authValidateRemindPassword') . '?id_f=remind_password');

		if (Request::IsPost() && Request::Check('email')) {
			$user = UserDAL::GetResult(UserDAL::GetDalDataObj(array('condition' => array('email' => Request::GetPost('email')))));
			if (empty($user)) {
				$this->RunShared('InfoFrame', array('info' => $this->t('No such user'), 'type' => 'ok'));
				return;
			}

			$user = $user[0];

			$dalClass = 'UserDAL';
			$dalClass = new $dalClass;
			$password = substr(md5(microtime()), 10, 7);



			$user->setPassword($dalClass->generatePassword($password));
			$mailer = new Mailer(MAIL_PORT);

			$this->smarty->assign('password', $password);
			$bodyHTML = $this->smarty->fetch('partial/Auth/RemindPasswordEmailHTML.tpl');

			$this->smarty->assign('password', $password);
			$bodyPlain = $this->smarty->fetch('partial/Auth/RemindPasswordEmailPlain.tpl');

			$mailer->SendEmail($bodyHTML, $bodyPlain, $this->t('Paswword reminder - tennizoom.com'), $user->getEmail());

			$dalClass->update($user->getDalDataObj());

			$this->RunShared('InfoFrame', array('info' => $this->t('A new password has been sent to your email address.'), 'type' => 'ok'));
			$this->addRedirectInfo($this->t('New password has been sent to your email address.'),'ok',Router::GenerateUrl('logIn'),0);
		}
	}

	public function ValidateRemindPasswordAction($param, $as_action = true) {
		if ($as_action)
			$param = array();

		$validator = new Validator($param);
		$validator->isEmpty('email', $this->t('Musisz podać adres email'));
		$validator->IsEmailAddress('email', $this->t('Podany adres jest nieprawidłowy'));

		$this->smarty->assign('js_values', $validator->getJsValues());
		$this->smarty->assign('id_form', Request::GetGet('id_f'));
		return $validator->getErrorList();
	}

}

